package com.liyk.shop.exception;

import com.liyk.shop.enums.ResponseStatusEnum;
import com.liyk.shop.response.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 全局异常捕捉处理
 *
 * @author lixk
 * @date 2018/10/11
 */
@ControllerAdvice
@Slf4j
public class GlobalControllerAdvice {

    @ResponseBody
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public Result errorHandler(MethodArgumentNotValidException ex, HttpServletRequest request, HttpServletResponse response) {
        proccess(request, response);
        BindingResult result = ex.getBindingResult();
        if (result.hasErrors()) {
            for (FieldError fieldError : result.getFieldErrors()) {
                return Result.custom(ResponseStatusEnum.PARAM_BIND.getCode(),ResponseStatusEnum.PARAM_BIND.getMsg(),ex.getMessage());
            }
        }
        return Result.serverException("MethodArgumentNotValidException");
    }

    @ResponseBody
    @ExceptionHandler(value = GenericException.class)
    public Result errorHandler(GenericException ex, HttpServletRequest request, HttpServletResponse response) {
        proccess(request, response);
        log.info("GenericException业务异常： "+ex.getMsg());
        ex.printStackTrace();
        return Result.fail(ex.getCode(), ex.getMsg());
    }

    /**
     * 全局异常后跨域解决
     * @param request
     * @param response
     */
    private void proccess(HttpServletRequest request, HttpServletResponse response) {
        String originHeader = request.getHeader("Origin");
        response.setCharacterEncoding("UTF-8");
        response.setHeader("Content-type", "application/json;charset=UTF-8");
        response.setStatus(200);
        response.setHeader("Access-Control-Expose-Headers", "verifyCode");
        response.setHeader("Access-Control-Allow-Origin", originHeader);
        response.setHeader("Access-Control-Allow-Credentials", "true");
        response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
        response.setHeader("Access-Control-Max-Age", "3600");
        response.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
    }
}

